<?php

namespace App\Http\Service;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\Exceptions\ApiException;
use App\Exceptions\CdjException;
use App\Org\Sms\ChuanglanSmsApi;
use App\Models\SchoolSuppliers;
use App\Models\PartnerSetting;
use App\Models\OperateLogs;
use App\Models\Setting;
use App\Models\Company;
use App\Models\User;
use Saas;


class SupplyService
{
    use AdminTrait;

    public $operateData;

    /**
     * @param 供应商列表
     * @param array $id
     * @return array
     * @throws CdjException
     */
    public function getList($params)
    {
        $params['school_audit_status'] = 1;
        $params['admin_audit_status']  = 0;
        $list                          = SchoolSuppliers::list($params);

        foreach ($list['list'] as &$value) {
            if (!empty($value['introduction_letters'])) {
                $value['introduction_letters'] = json_decode($value['introduction_letters'], true);
            }
        }

        return $list;
    }

    /**
     * @desc 供应商审核
     * @param array $params
     * @return array
     * @throws CdjException
     */
    public function uptown($params)
    {
        $validator = Validator::make($params, ['id' => 'required|numeric', 'admin_audit_status' => 'required|numeric',]);
        if ($validator->fails())
            throw new CdjException($validator->errors()->first(), 40001);

        $this->checkFillData($params);

        DB::beginTransaction();
        try {
            // 添加供应商基础信息
            $companyInfo = Company::create($this->operateData);

            //生成默认管理员
            $password  = Hash::make($this->operateData['mobile']);
            $user_data = [
                'name'       => $this->operateData['name'],
                'password'   => $password,
                'mobile'     => $this->operateData['mobile'],
                'role_id'    => 1,
                'username'   => 'admin',
                'company_id' => $companyInfo->id,
                'status'     => 1,
            ];
            User::create($user_data);

            // 生成默认配置
            $set_data = [
                'id'         => $companyInfo->id,
                'site_title' => $this->operateData['company_name'],
            ];
            Setting::add($set_data);

            // 插入商城配置
            if (in_array($this->operateData['model'], [2, 3])) {
                $data_partner = [
                    'company_id' => $companyInfo->id,
                ];
                PartnerSetting::create($data_partner);
            }

            // 审核成功
            $auditData = [
                'admin_audit_status' => $params['admin_audit_status'],
                'admin_audit_remark' => isset($params['admin_audit_remark']) ? $params['admin_audit_remark'] : '',
                'supplier_id'        => $companyInfo->id,
                'updated_at'         => time(),
            ];
            SchoolSuppliers::where('id', $params['id'])->update($auditData);

            // 短信通知
            $info = SchoolSuppliers::where('id', $params['id'])->first();
            $cdate = $info ? $info->created_at : '';
            $sendSmsSrv     = new ChuanglanSmsApi();
            $str = "你好，%s！你于 %s 入驻申请已通过审核";
            $content = sprintf($str, $user_data['name'], $cdate);
            $sendSmsSrv->sendSMS($user_data['mobile'], $content);

            DB::commit();
            return ['res' => true];
        } catch (\Exception $e) {
            DB::rollBack();
            throw new CdjException('审核失败，errMsg：' . $e->getMessage(), 40002);
        }
    }

    private function checkFillData($params)
    {
        $rules = [
            'id'          => 'required',
            'domain_name' => 'required|string',
        ];

        $validator = Validator::make($params, $rules);
        if ($validator->fails())
            throw new CdjException($validator->errors()->first(), 40001);

        $applyInfo = SchoolSuppliers::where('id', $params['id'])->first();
        if (empty($applyInfo))
            throw new CdjException('供应商申请信息不存在', 40002);

        if (empty($applyInfo['phone_number'])) {
            throw new CdjException('负责人手机号不能为空', 40002);
        }

        $info = Company::where('mobile', $applyInfo['phone_number'])->first();
        if ($info)
            throw new CdjException('负责人手机号已存在', 40002);

        $exists = Company::where('domain_name', $params['domain_name'])->count();
        if ($exists)
            throw new CdjException('域名已存在', 40002);

        // 检测域名是否已解析
        $isExists = $this->domainIsExists($params['domain_name']);
        if (!$isExists)
            throw new CdjException('域名还未解析，请添加域名解析', 40002);

        $unixTime          = time();
        $this->operateData = [
            'company_name'     => $applyInfo['company_name'] ?? '',
            'company_fullname' => $applyInfo['company_name'] ?? '',
            'name'             => $applyInfo['contact_name'] ?? '',
            'mobile'           => $applyInfo['phone_number'] ?? '',
            'status'           => 1,
            'audit'            => 1,
            'address'          => '',
            'base_address'     => '100000',
            'start_time'       => $unixTime,
            'end_time'         => $unixTime + 10 * 86400,
            'domain_name'      => $params['domain_name'] ?? '',
            'model'            => 3,
            'renewal_money'    => 0.01,
            'commission_rate'  => '6‰',
            'created_at'       => $unixTime,
            'updated_at'       => $unixTime,
        ];

        return $this->operateData;
    }

    /**
     * @param 供应商详情
     * @param array $id
     * @return array
     * @throws CdjException
     */
    public function getDetail($params)
    {
        if (!isset($params['id']) && !$params['id']) {
            throw new CdjException('供应商ID不能为空', 40001);
        }

        $info = SchoolSuppliers::where('id', $params['id'])->first();
        if (!$info)
            throw new CdjException('供应商信息不存在', 40002);

        $info->introduction_letters = json_decode($info->introduction_letters, true);

        return $info;
    }
}
